(function ($) {
    $(document).ready(function () {
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initializeMenu);
    });
})(jQuery);

function initializeMenu() {
    $('.menu li.has-sub>a').on('click', function () { openCloseMenu(this); });
    $('.menu>ul>li.has-sub>a').append('<span class="holder"></span>');
    openSavedMenu();
}

function openCloseMenu(menu, duration) {
    if (duration === undefined) duration = 400;

    $(menu).removeAttr('href');
    if (duration == 0) {
        $(menu).children('.holder').addClass('notransition');
        $(menu).parent('li').siblings('li').children('a').children('.holder').addClass('notransition');
    } else {
        $(menu).children('.holder').removeClass('notransition');
        $(menu).parent('li').siblings('li').children('a').children('.holder').removeClass('notransition');
    }

    var element = $(menu).parent('li');
    if (element.hasClass('open')) {
        element.removeClass('open');
        element.find('li').removeClass('open');
        element.find('ul').slideUp(duration);
        setOpenMenu('');
    }
    else {
        element.addClass('open');
        element.children('ul').slideDown(duration);
        element.siblings('li').children('ul').slideUp(duration);
        element.siblings('li').removeClass('open');
        element.siblings('li').find('li').removeClass('open');
        element.siblings('li').find('ul').slideUp(duration);
        setOpenMenu(element.attr('id'));
    }
}

function setOpenMenu(menuId) {
    PageMethods.SaveOpenedMenuId(menuId);
}

function openSavedMenu() {
    PageMethods.ReadOpenedMenuId(function (menuId) {
        if (menuId && menuId != '') {
            openCloseMenu($('#' + menuId + '>a'), 0);
        }
    });
}
